<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

use Unirest\Request AS API;
use Cache;

class CampusOauth2Controller extends Controller
{

    //授权页
    public function authPage(Request $request)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id'    => 'required|integer|min:1',
                'state'      => 'required|string|min:1',
                'system_cat' => 'string|min:1'
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        $header = [
            "host"          => "campus",
            "authorization" => "Bearer ".env("ACCESS_TOKEN")
        ];
        
        if(isset($input["system_cat"])){
            $userId = $input["user_id"];
            $systemCat = $input["system_cat"];
            $userSystemResponse = API::get(env("PTIME_API")."/user/$userId/system",$header,["system_cat"=>$systemCat]);
            if(!empty($userSystemResponse->body->result)){
                $campusId  = $userSystemResponse->body->result->campus_id;
                $systemId  = $userSystemResponse->body->result->system_id;
            }
        }

        $campusResponse = API::get(env("PTIME_API")."/campus",$header);
        if(!empty($campusResponse->body->result))
            $campusIdTemp = !empty($campusId)?$campusId:$campusResponse->body->result[0]->id;

        if(!empty($campusIdTemp)){
            $body = !empty($input["system_cat"])?["system_cat"=>$input["system_cat"]]:[];
            $systemResponse = API::get(env("PTIME_API")."/campus/$campusIdTemp/system",$header,$body);
        }

        return view('campus/auth',[
            "campus"        => !empty($campusResponse->body->result)?$campusResponse->body->result:[],
            "system"        => !empty($systemResponse->body->result)?$systemResponse->body->result:[],
            "user_id"       => $input["user_id"],
            "state"         => $input["state"],
            "system_cat"    => !empty($input["system_cat"])?$input["system_cat"]:"",
            "campus_id"     => !empty($campusId)?$campusId:"",
            "system_id"     => !empty($systemId)?$systemId:""
        ]);
    }

}